import { defineStore } from "pinia";
import { reqLogin, reqUserInfo, reqLogout } from "@/apis/user";
import type { LoginForm, LoginResponseData, UserInfoResponseData } from "@/apis/user/types";
import type { UserState } from "./types/types";
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from "@/utils/token";
import { constantRoutes } from "@/routers/routes";

const useUserStore = defineStore("user", {
  state: (): UserState => {
    return {
      token: GET_TOKEN(),
      routes: constantRoutes,
      username: "",
      avatar: "",
    };
  },
  actions: {
    // 请求登录
    async userLogin(data: LoginForm) {
      const res: LoginResponseData = await reqLogin(data);
      if (res.code === 200) {
        this.token = res.data as string;
        SET_TOKEN(this.token);
        return res.message;
      } else {
        return Promise.reject(new Error(res.data));
      }
    },

    // 获取用户信息
    async useInfo() {
      const res: UserInfoResponseData = await reqUserInfo();
      if (res.code === 200) {
        // console.log('res', res)
        this.username = res.data.name;
        this.avatar = res.data.avatar;
        return "ok";
      } else {
        return Promise.reject(new Error(res.message));
      }
    },

    // 退出登录
    async userLogout() {
      // 调用退出登录接口
      const res: any = await reqLogout();
      if (res.code === 200) {
        this.token = "";
        this.username = "";
        this.avatar = "";
        // 清除本地缓存的token
        REMOVE_TOKEN();
        return 'ok'
      }else {
        return Promise.reject(new Error(res.message))
      }
    },
  },

  getters: {},
});

export default useUserStore;
